package com.polaris.live.popup

import android.content.Context
import android.graphics.Color
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.view.View.OnFocusChangeListener
import android.view.inputmethod.InputMethodManager
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.SpanUtils
import com.blankj.utilcode.util.StringUtils
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BottomPopupView
import com.polaris.live.R.color
import com.polaris.live.R.layout
import com.polaris.live.adapter.NikeNameRandomAdapter
import com.polaris.live.common.R
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.constant.AppConst
import com.polaris.live.common.constant.BizEventConst
import com.polaris.live.common.event.EventMessage
import com.polaris.live.common.ext.convertArabicDigitsToNormal
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.manager.CoroutineScopeManager
import com.polaris.live.common.network.manualRequest
import com.polaris.live.common.util.DateUtils.Companion.convertTimestampToString
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.common.util.ViewUtils
import com.polaris.live.common.util.loading.LoadingUtils
import com.polaris.live.constant.UserConst
import com.polaris.live.databinding.PopupCompleteProfileBinding
import com.polaris.live.net.userService
import com.polaris.live.resp.go_resp.QuickModifyBean
import com.polaris.live.translation.R.string
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale

/**
 * 完善资料弹窗
 *
 * @author Created by 半仙 on 2023/8/17/017 16:19
 */
class CompleteTheProfilePopup(
    private val context: Context,
    private val mOnIsOK: () -> Unit,
) : BottomPopupView(context) {

    private lateinit var mBinding: PopupCompleteProfileBinding

    private val mAdapter: NikeNameRandomAdapter by lazy { NikeNameRandomAdapter() }

    private var mNickname = ""

    private var mGender: Int? = null

    private var mIsShowBirthday = false

    private var mIsFirstClick = false

    private var mUpdateJob: Job? = null

    private var mCompleteJob: Job? = null

    override fun getImplLayoutId(): Int {
        return layout.popup_complete_profile
    }

    override fun onCreate() {
        super.onCreate()
        mBinding = PopupCompleteProfileBinding.bind(popupImplView)

        mBinding.recyclerView.adapter = mAdapter

        initListener()
        initObserver()
        initNetWork()
        initData()
    }

    private fun initNetWork() {
        //判断当前广告来源
        val trafficSourceType = UserManager.getUser().flag?.trafficSourceType
        if (trafficSourceType == UserConst.FlagFrom.FB_COME) {
            mBinding.root.post {
                mBinding.manSelect.performClick()
            }
        } else {
            mCompleteJob = CoroutineScopeManager.mainScope.launch {
                try {
                    manualRequest({ userService.getUserTrafficSource() },
                        {
                            UserManager.getUser().flag?.trafficSourceType = it.trafficSourceType

                            if (it.selectedMale) {
                                mBinding.root.post {
                                    mBinding.manSelect.performClick()
                                }
                            }
                        }, {})
                } finally {
                    if (mCompleteJob == coroutineContext[Job]) {
                        mCompleteJob = null
                    }
                }
            }
        }
    }

    private fun initListener() {
        mAdapter.setOnItemClickListener { _, _, position ->
            mBinding.llNikeName.setBackgroundResource(R.drawable.r12_back_fff1f1f1)
            mBinding.nickNameImg.setImageResource(R.drawable.ic_correct)
            mNickname = mAdapter.data[position].nickname.toString()
            mBinding.nickName.setText(mAdapter.data[position].nickname.toString())
            mAdapter.data[position].nickname?.length?.let { mBinding.nickName.setSelection(it) }
        }

        mBinding.nickName.onFocusChangeListener =
            OnFocusChangeListener { v, hasFocus ->
                if (!hasFocus) {
                    hideKeyboard(v)
                }
            }

        mBinding.llBg.setOnSingleClickListener {
            mBinding.nickName.clearFocus()
        }
    }

    //隐藏软键盘并让editText失去焦点
    private fun hideKeyboard(view: View) {
        val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager?
        imm?.hideSoftInputFromWindow(view.windowToken, 0)
    }

    fun initObserver() {
        val topActivity = ViewUtils.getAliveTopActivity()
        topActivity?.let {
            KeyboardUtils.registerSoftInputChangedListener(topActivity) {
                if (it != 0 && !mIsFirstClick) {
                    mIsFirstClick = true
                    mBinding.nickName.setText("")
                }
            }
        }
    }

    private fun initData() {
        mBinding.apply {

            nickName.post {
                nickName.clearFocus()
            }

            nickNameTitle.text =
                SpanUtils.with(nickNameTitle).append(StringUtils.getString(string.your_nickname))
                    .append(" *").setForegroundColor(ColorUtils.getColor(color.fe1849)).create()

            nickName.setText("${UserManager.getUser().nickname}")
            nickName.setTextColor(Color.parseColor("#A7A8AD"))
            nickName.addTextChangedListener(object : TextWatcher {
                override fun beforeTextChanged(
                    s: CharSequence?,
                    start: Int,
                    count: Int,
                    after: Int,
                ) {
                }

                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
                override fun afterTextChanged(s: Editable?) {
                    // 在文本改变之后的回调
                    val userInput = s.toString()
                    // 检查是否以空格开头或结尾
                    if (userInput.startsWith(" ") || userInput.endsWith(" ")) {
                        // 如果以空格开头或结尾，移除空格
                        val trimmedText = userInput.trim { it <= ' ' }
                        nickName.setText(trimmedText)
                        nickName.setSelection(trimmedText.length) // 将光标移至末尾
                    }
                    val size = nickName.text.length
                    if (size in 2..20) {
                        nickNameImg.visibility = VISIBLE
                    } else {
                        nickNameImg.visibility = GONE
                    }
                    nickName.setTextColor(Color.parseColor("#202028"))
                }
            })

            birthdayTitle.text =
                SpanUtils.with(birthdayTitle).append(StringUtils.getString(string.your_birthday))
                    .append(" *").setForegroundColor(ColorUtils.getColor(color.fe1849)).create()
            val birthday = UserManager.getUser().birthday

            if (birthday == null) {
                val calendar = Calendar.getInstance()
                calendar.add(Calendar.YEAR, -18)

                val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
                val formattedDate = dateFormat.format(calendar.time)

                birthdaySelect.text = formattedDate.convertArabicDigitsToNormal()
            } else {
                val dateString = convertTimestampToString(birthday)
                birthdaySelect.text = dateString?.convertArabicDigitsToNormal()
            }

            genderTitle.text =
                SpanUtils.with(genderTitle).append(StringUtils.getString(string.your_gender))
                    .append(" *").setForegroundColor(ColorUtils.getColor(color.fe1849)).create()


            manSelect.setOnSingleClickListener {
                mBinding.nickName.clearFocus()
                if (mGender != AppConst.UserSex.MAN) {
                    mGender = AppConst.UserSex.MAN
                    manSelectImg.isSelected = true
                    womanSelectImg.isSelected = false
                    manSelectMark.visibility = View.VISIBLE
                    womanSelectMark.visibility = View.GONE
                    manSelect.alpha = 1f
                    womanSelect.alpha = 0.4f
                }
            }
            womanSelect.setOnSingleClickListener {
                mBinding.nickName.clearFocus()
                if (mGender != AppConst.UserSex.WOMAN) {
                    mGender = AppConst.UserSex.WOMAN
                    manSelectImg.isSelected = false
                    womanSelectImg.isSelected = true
                    manSelectMark.visibility = View.GONE
                    womanSelectMark.visibility = View.VISIBLE
                    manSelect.alpha = 0.4f
                    womanSelect.alpha = 1f
                }
            }

            conTime.setOnSingleClickListener {
                mBinding.nickName.clearFocus()
                mIsShowBirthday = true
                XPopup.Builder(context)
                    .isDestroyOnDismiss(true)
                    .asCustom(
                        DataSelectPopup(
                            context,
                            mOnSelectCallBack = { year, month, day ->
                                birthdaySelect.text =
                                    "${year}-${month}-${day}".convertArabicDigitsToNormal()
                                birthdaySelect.setTextColor(ColorUtils.getColor(color.f202028))
                                birthdayImg.visibility = VISIBLE
                            }, birthday
                        )
                    )
                    .show()
            }

            updataMessage.setOnSingleClickListener {
                if (mGender != null) {
                    val toString = birthdaySelect.text.toString()
                    val infoModifyBean = QuickModifyBean(
                        nickname = nickName.text.toString(),
                        sex = mGender,
                        birthday = toString,
                        defaultBirthday = if (mIsShowBirthday) 0 else 1
                    )

                    mUpdateJob = CoroutineScopeManager.mainScope.launch {
                        LoadingUtils.showLoadingDialog(
                            this@CompleteTheProfilePopup.context,
                            context.getString(string.loading),
                            useView = false
                        )

                        try {
                            manualRequest(
                                { userService.quickModify(infoModifyBean) },
                                { updateSuccess() },
                                { ToastGravity.showGravity(it.errorMsg) }
                            )
                        } finally {
                            LoadingUtils.dismissLoadingDialog()

                            if (mUpdateJob == coroutineContext[Job]) {
                                mUpdateJob = null
                            }
                        }
                    }
                } else {
                    ToastGravity.showGravity(StringUtils.getString(string.please_complete_the_information))
                }
            }
        }
    }

    private fun updateSuccess() {
        if (mGender != null) {
            UserManager.getUser().sex = mGender as Int
        }
        mOnIsOK.invoke()
        EventBus.getDefault().post(EventMessage(BizEventConst.INFO_UPDATA))
        dismiss()
    }

    override fun onDismiss() {
        super.onDismiss()

        mUpdateJob?.cancel()
        mUpdateJob = null

        mCompleteJob?.cancel()
        mCompleteJob = null
    }
}